<?php

/**
 * This is the model class for table "pages".
 *
 * The followings are the available columns in table 'pages':
 * @property integer $id
 * @property integer $chapterId
 * @property integer $sequence
 * @property string $subSequence
 * @property string $createdAt
 * @property string $updatedAt
 */
class Page extends ActiveRecord {

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Page the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'pages';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('chapterId, sequence', 'numerical', 'integerOnly'=>true),
			array('subSequence', 'length', 'max'=>1),
			array('chapterId, sequence', 'safe', 'on'=>'search'),
			array('sequence', 'required', 'on'=>'insertLanguage'),
			array(
				'sequence',
				'numerical',
				'integerOnly'=>true,
				'on'=>'insertLanguage'
			),
			array('subSequence', 'safe', 'on'=>'insertLanguage'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'chapter'=>array(self::BELONGS_TO, 'Chapter', 'chapterId'),
			'languages'=>array(self::HAS_MANY, 'Language', 'pageId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id'=>'ID',
			'chapterId'=>'Chapter',
			'sequence'=>'Page',
			'subSequence'=>'Sub Page',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($order = false) {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('chapterId', $this->chapterId);
		$criteria->compare('sequence', $this->sequence);
		if ($order) {
			$criteria->order = $order;
		}
		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
			));
	}

	public function getHumanSequence() {
		return $this->sequence . $this->subSequence;
	}

	protected function afterSave() {
		parent::afterSave();
		$this->chapter->save(false);
	}
}